package io.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: RedisUtils
 * Package: io.redis.util
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/16 23:17
 * @Version 1.0
 */

@Component
public class RedisUtils {
    // 通过构造方法注入
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * String类型存入
     *
     * @param key 键
     * @param value 值
     * @return true：成功；false：失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return StringUtils.isEmpty(key) ? null :
                redisTemplate.opsForValue().get(key);
    }
    /**
     * hash类型存入
     * @param key 键
     * @param field 字段
     * @param value 值
     * @return
     */
    public boolean hset(String key,Object field,Object value) {
        try {
            redisTemplate.opsForHash().put(key,field,value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * hash类型值获取
     * @param key 键
     * @param field 字段
     * @return
     */
    public Object hget(String key,Object field) {
        return StringUtils.isEmpty(key) ? null :
                redisTemplate.opsForHash().get(key,field);
    }
    /**
     * 删除指定的key
     * @param key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }
    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean exist(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 设置key的过期时间
     * @param key
     * @param seconds
     * @return
    7.5 测试RedisUtils
     */
    public boolean expire(String key,long seconds) {
        try {
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 获取当前key的存活时间
     * @param key
     * @return
     */
    public long ttl(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
}
